package com.purchase.util.wxpay.app;

import com.purchase.util.PropertiesUtil;
import com.purchase.util.wxpay.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class WxpayHandlerAPP {

    private WXPayAPP wxpay;
    private WXPayConfigImplAPP config;

    public WxpayHandlerAPP() throws Exception {
        config = WXPayConfigImplAPP.getInstance();
        wxpay = new WXPayAPP(config, null, false, Boolean.parseBoolean(PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.useSandbox")));
    }

    /**
     * 统一下单
     */
    public Map<String, String> doUnifiedOrder(Map<String, Object> paramMap) {
        Map<String, String> data = new HashMap<>();
        data.put("body", String.valueOf(paramMap.get("goodsBody")));
//        data.put("openid", String.valueOf(paramMap.get("openid")));
        data.put("out_trade_no", String.valueOf(paramMap.get("id")));
        data.put("total_fee", yuan2fen(String.valueOf(paramMap.get("totalFee"))));
        data.put("spbill_create_ip", PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.ip"));
        data.put("notify_url", PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.notifyUrl"));
        data.put("trade_type", String.valueOf(paramMap.get("tradeType")));

        Map<String, String> map = null;
        try {
            map = wxpay.unifiedOrder(data);

            //二次签名发给APP
            Map<String, String> signMap = new LinkedHashMap<>();
            String nonceStr = WXPayUtil.generateNonceStr();
            //APP
            String appidAPP = PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.appid.APP");
            map.put("appid", appidAPP);
            map.put("partnerid", PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.mchid.APP"));
            map.put("prepayid", map.get("prepay_id"));
            map.put("package", "Sign=WXPay");
            map.put("noncestr", nonceStr);
            map.put("timestamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));

            signMap.put("appid", map.get("appid"));
            signMap.put("partnerid", map.get("partnerid"));
            signMap.put("prepayid", map.get("prepayid"));
            signMap.put("package", map.get("package"));
            signMap.put("noncestr", map.get("noncestr"));
            signMap.put("timestamp", map.get("timestamp"));
            String appPaySign = WXPayUtil.generateSignature(signMap, config.getKey());
            map.put("sign", appPaySign);

        } catch (Exception e) {
            log.error("微信支付下单异常", e);
            map.put("return_msg", map.get("return_msg"));
        }
        return map;
    }

    /**
     * 申请退款
     */
    public Map<String, String> refund(Map<String, Object> paramMap) {
        Map<String, String> data = new HashMap<>();
        data.put("transaction_id", String.valueOf(paramMap.get("transaction_id")));//微信订单号
        data.put("out_trade_no", String.valueOf(paramMap.get("out_trade_no")));//商户订单号
        data.put("out_refund_no", String.valueOf(paramMap.get("out_refund_no")));//商户退款单号
        data.put("total_fee", yuan2fen(String.valueOf(paramMap.get("total_fee"))));//总金额
        data.put("refund_fee", yuan2fen(String.valueOf(paramMap.get("total_fee"))));//退款金额
        data.put("refund_desc", String.valueOf(paramMap.get("refund_desc")));//退款原因
        data.put("notify_url", PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.refundNotifyUrl"));

        Map<String, String> map = null;
        try {
            map = wxpay.refund(data);

        } catch (Exception e) {
            log.error("微信支付申请退款异常", e);
            map.put("return_msg", map.get("return_msg"));
        }
        return map;
    }

    public Map<String, String> orderQuery(Map<String, Object> paramMap) {
        Map<String, String> data = new HashMap<>();
        data.put("transaction_id", String.valueOf(paramMap.get("transaction_id")));//微信订单号
        data.put("out_trade_no", String.valueOf(paramMap.get("out_trade_no")));//商户订单号

        Map<String, String> map = null;
        try {
            map = wxpay.orderQuery(data);
        } catch (Exception e) {
            log.error("微信支付查询订单异常", e);
            map.put("return_msg", map.get("return_msg"));
        }
        return map;
    }

    public Map<String, String> refundQuery(Map<String, Object> paramMap) {
        Map<String, String> data = new HashMap<>();
        data.put("transaction_id", String.valueOf(paramMap.get("transaction_id")));//微信订单号

        Map<String, String> map = null;
        try {
            map = wxpay.refundQuery(data);
        } catch (Exception e) {
            log.error("微信支付查询退款异常", e);
            map.put("return_msg", map.get("return_msg"));
        }
        return map;
    }

    private static String yuan2fen(String amount) {
        String currency = amount.replaceAll("[$￥,]", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }

    public static void main(String[] args) {
        System.out.println(yuan2fen("11.00"));
    }

}
